# -*- coding: utf-8 -*-
"""
Created on Tue May 21 19:58:19 2019

@author: Administrator
"""

import numpy as np
# ndarray 数组的变换
# 对于创建后的ndarray，可以对其进行维度变换和类型变换

# 1.维度变换
# reshaped_ndarray ndarray.reshape(shape)
# 返回一个新形状shape的ndarray，原数组不变
# void ndarray.resize(shape)
# 同上，但修改原数组

a = np.ones((2,3,4), dtype = np.int32)
print(a.ndim)

reshaped_a = a.reshape((3,8))
print(reshaped_a)
print(a) # 原数组不变

a.resize((3,8))
print(a) # 原数组改变

# 注意：元素个数保证不变：2*3*4 = 3*8

# ndarray.swapaxes(ax1, ax2)
# 将数组n个维度中两个维度进行调换

# ndarray ndarray.flatten()
# 对数组降维，返回折叠后的一维数组，原数组不变
a = np.full((2,3,4), 8)

flatten_a = a.flatten()
print(flatten_a) # 折叠成一维数组
print(type(flatten_a)) # <class 'numpy.ndarray'>
print(a) # 原数组不变

# 2.元素类型变换
# new_ndarray ndarray.astype(new_type)
# 原数组
a = np.ones((2,3,4), dtype=np.int)
print(a.dtype) # int32

# 变换数据类型
float_a = a.astype(np.float)
print(float_a.dtype) # float64

# 3.数据结构转换
# ndarray => list
# list ndarray.tolist()
a = np.full((2,3,4), 25, dtype=np.int)
a_list = a.tolist()

print(a_list)
print(type(a_list)) # <class 'list'>



# 小结
# ndarray的变换：
# - 维度变换：reshape(shape)|resize(shape)/swapaxes()/flatten()
# - 元素类型变换：astype(dtype)
# - 数据结构变换：tolist()